package com.boruan.shengtangfeng.core.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.entity.*;


import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import com.boruan.shengtangfeng.core.vo.mapper.TalkVideoVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ToAuditVideoVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoCommentVoMapper;


import org.beetl.sql.core.SQLManager;

import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.boruan.shengtangfeng.core.dto.VideoCategoryDto;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IVideoService;
import com.boruan.shengtangfeng.core.vo.mapper.VideoCategoryVoMapper;

/**
 *
 * @author liuguangqiang
 * @date 2016年8月10日 上午9:36:16
 */
@Service
@Transactional(readOnly = true)
public class VideoService implements IVideoService {
	private static Logger logger = LoggerFactory.getLogger(VideoService.class);
	@Autowired
    private IFavoritesDao favoritesDao;
	@Autowired
	private IVideoDao videoDao;
	@Autowired
	private IVideoCategoryDao videoCategoryDao;
	@Autowired
	private ILogService logService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private IVideoCommentDao iVideoCommentDao;
	@Autowired
	private IVideoClassDao videoClassDao;
	@Autowired
	private IVideoGradeDao videoGradeDao;
	@Autowired
	private IVideoFriendDao videoFriendDao;
	@Autowired
	private IMusicDao musicDao;
	@Autowired
	private IMusicUseDao musicUseDao;
	@Autowired
	private IUserDao userDao;
	@Autowired
	private ALiYunUtils aLiYunUtils;
	@Autowired
	private IAccoladeDao accoladeDao;
	@Autowired
	private IAttentionDao attentionDao;

	/**
	 *  后台查询用户信息
	 * @author liuguangqiang
	 * @date 2016年8月10日 上午9:36:16
	 */
	@Override
	public Video findId(Long id) {
		return videoDao.unique(id);
	}

	@Override
	public Video findById(Long id) {
		return videoDao.findById(id);
	}


	@Override
	public void pageQuery(PageQuery<Video> pageQuery,Video video) {
		pageQuery.setParas(video);
		videoDao.pageQuery(pageQuery);
	}



	@Override
	@Transactional(readOnly = false)
	public boolean save(Video video) {
		try {
			if (video.getId()==null) {
				KeyHolder kh=videoDao.insertReturnKey(video);
				video.setId(kh.getLong());
				calculateDuration(video);
				aLiYunUtils.aliyunVideoSyncCheck(video.getContent(),video.getId());
			}else{
				videoDao.updateById(video);
				aLiYunUtils.aliyunVideoSyncCheck(video.getContent(),video.getId());
			}
			return true;

		} catch (Exception e) {
			return false;
		}
	}

	@Override
	@Transactional(readOnly = false)
	public boolean saveSmall(Video video,String classes,String friendIds,Long userId,Long classId,Long musicId) {
		try {
			if (video.getId()==null) {
				KeyHolder kh=videoDao.insertReturnKey(video);
				video.setId(kh.getLong());
				if (friendIds!=null && friendIds.length()>0){
					String[] split = friendIds.split(",");
					for (String s : split) {
						VideoFriend videoFriend = new VideoFriend();
						videoFriend.setIsRead(0);
						videoFriend.setVideoId(kh.getLong());
						videoFriend.setFriendId(Long.valueOf(s));
						videoFriend.setCreateBy(userId.toString());
						videoFriend.setCreateTime(new Date());
						videoFriend.setIsDeleted(false);
						videoFriendDao.insertTemplate(videoFriend);
					}
				}
				aLiYunUtils.aliyunVideoSyncCheck(video.getContent(),video.getId());
			}else{
				videoDao.updateById(video);
				aLiYunUtils.aliyunVideoSyncCheck(video.getContent(),video.getId());
			}
			if (musicId!=null){
				Music music = musicDao.unique(musicId);
				music.setClickNum(music.getClickNum()+1);
				music.setUpdateTime(new Date());
				music.setUpdateBy(userId.toString());
				musicDao.updateTemplateById(music);
				MusicUse use = new MusicUse();
				use.setMusicId(musicId);
				use.setUserId(userId);
				use.setUserTime(new Date());
				use.setCreateBy(userId.toString());
				use.setCreateTime(new Date());
				use.setIsDeleted(false);
				musicUseDao.insertTemplate(use);
			}
			calculateDuration(video);
			if(video.getScope()==2){
				upVideoClasses(video,classes);
			}
			if (video.getScope()==0){
				if (classId!=null){
					upVideoClasses(video,classId.toString());
				}
			}
			calculateDuration(video);
			return true;
		} catch (Exception e) {
			return false;
		}
	}



	@Override
	public List<Video> findByTemplate(Video video) {
		return videoDao.template(video);
	}
	@Override
	@Transactional(readOnly = false)
	public void deleteVideo(Long videoId, Long userId) {
		Video video=videoDao.single(videoId);
		video.setUpdateBy(userId.toString());
		video.setUpdateTime(new Date());
		video.setIsDeleted(true);
		videoDao.updateTemplateById(video);
		noticeService.addNotice(2, 2, videoId, video.getPublishId(), "您上传的视频被删除","您上传的视频存在违规，已被删除");
		Log sysLog = new Log();
		sysLog.setContent("删除视频");
		sysLog.setCreateTime(new Date());
		sysLog.setOperater(userId);
		sysLog.setObjectId(videoId);
		sysLog.setLogType(Log.LogType.ADMIN);
		sysLog.setOperateType(Log.OperateType.DELETE);
		logService.save(sysLog);
	}

	@Override
	public void pageQueryCategory(PageQuery<VideoCategory> pageQuery, VideoCategory videoCategory) {
		pageQuery.setParas(videoCategory);
		videoCategoryDao.pageQuery(pageQuery);
	}

	@Override
	public List<VideoCategory> getCategoryList(VideoCategory videoCategory) {
		return videoCategoryDao.getList(videoCategory);
	}


	@Override
	public List<Video> findClosely(Video video) {
		return videoDao.findClosely(video);
	}



	// ================= 后台 ===================
	@Override
	@Transactional(readOnly = false)
	public void addVideo(Video po, Long userId) {

		if (null != po.getId()) {
//			po.setPublisher(user.getName());
//			po.setPublisherIcon(user.getHeadImage());
			po.setPublishDate(new Date());
			po.setIsDeleted(false);
			po.setUpdateBy(userId.toString());
			po.setUpdateTime(new Date());
			videoDao.updateTemplateById(po);
		} else {
		    po.setPublishId(1L);
		    po.setUploadType(0);
			po.setPublishDate(new Date());
			po.setCreateBy(userId.toString());
			po.setIsDeleted(false);
			po.setCreateTime(new Date());
			videoDao.insertTemplate(po);
		}

	}

	@Override
	public List<VideoCategoryVo> getCategory(Integer type) {
		VideoCategory po = new VideoCategory();
		po.setIsDeleted(false);
		po.setType(type);
		return VideoCategoryVoMapper.MAPPER.toVo(videoCategoryDao.getList(po));
	}

	/**
	 * 获取全部视频分类
	 *
	 * @return
	 */
	@Override
	public List<VideoCategoryVo> getAllCategory() {
		VideoCategory po = new VideoCategory();
		po.setIsDeleted(false);
		return VideoCategoryVoMapper.MAPPER.toVo(videoCategoryDao.getList(po));
	}

	@Override
	@Transactional(readOnly = false)
	public void updateVideo(Long id, Integer type, Long userId) {

		Video po = new Video();
		po.setId(id);
		po.setUpdateBy(userId.toString());
		po.setUpdateTime(new Date());
		if (type == 0) {
			po.setStatus(1);
		} else if (type == 1) {
			po.setStatus(0);
		} else if (type == 2) {
			po.setRecommend(true);
		} else if (type == 3) {
			po.setRecommend(false);
		} else if (type == 4) {
			po.setIsDeleted(true);
		}
		videoDao.updateTemplateById(po);
	}

	@Override
	@Transactional(readOnly = false)
	public void saveCategory(VideoCategory videoCategory) {
		if (videoCategory.getId() == null) {
			KeyHolder kh = videoCategoryDao.insertReturnKey(videoCategory);
			videoCategory.setId(kh.getLong());
		} else {
			videoCategoryDao.updateTemplateById(videoCategory);
		}
	}
	@Override
	public VideoCategory getCategory(Long categoryId) {
		return videoCategoryDao.unique(categoryId);
	}

	@Override
	public void pageQueryCategory(PageQuery<VideoCategory> pageQuery, VideoCategoryDto videoCategoryDto) {
		pageQuery.setParas(videoCategoryDto);
		videoCategoryDao.pageQuery(pageQuery);
	}


	/**
	 * @description: 获取关注人的文章
	 * @Param
	 * @return
	 * @author KongXH
	 * @date 2020/8/18 10:59
	 */
	@Override
	public void pageAttentionVideo(PageQuery<Video> pageQuery,Long userId) {
		pageQuery.setPara("userId", userId);
		pageQuery.setPara("searchNoBlack", userId);
		videoDao.pageAttentionVideo(pageQuery);
	}

    @Override
    public Long templateCount(Video video) {
        return videoDao.templateCount(video);
    }

    @Override
    public Long getFavoritesCount(Long userId) {
        return favoritesDao.getFavoritesVideoCount(userId);
    }
    @Override
    public void pageFavoritesVideo(PageQuery<Video> pageQuery,Long userId) {
        pageQuery.setPara("userId",userId);
        videoDao.pageFavoritesVideo(pageQuery);
    }
    @Override
    public void pageAccoladeVideo(PageQuery<Video> pageQuery,Long userId) {
        pageQuery.setPara("userId",userId);
        videoDao.pageAccoladeVideo(pageQuery);
    }
    
    /**
     * 延时计算视频时长
     */
    @Override
    @Transactional(readOnly = false)
    public boolean calculateDuration(Video video) {
        if (!Global.VIDEO_THREAD_RUN) {
            System.out.println("视频线程未启动，start");
            CalculateVideoDurationThread writeLogThread=new CalculateVideoDurationThread(videoDao);
            writeLogThread.start();
            Global.VIDEO_THREAD_RUN=true;
        }
        return Global.videoQueue.offer(video);
    }


    @Override
	@Transactional(readOnly = false)
    public boolean upVideoClasses(Video video,String classes){
		videoClassDao.createLambdaQuery().andEq(VideoClass::getVideoId,video.getId()).delete();
		String[] classId = classes.split(",");
		List<VideoClass> list = new ArrayList<VideoClass>();
		for (String s : classId) {
			VideoClass temp = new VideoClass();
			temp.setClassId(Long.valueOf(s));
			temp.setVideoId(video.getId());
			temp.setCreateTime(new Date());
			temp.setIsDeleted(false);
			temp.setCreateBy(video.getPublisher());
			list.add(temp);
		}
		videoClassDao.insertBatch(list);
    	return true;
	}

	/**
	 * 查看用户待审核视频
	 *
	 * @param pageQuery
	 */
	@Override
	public void pageToAuditVideo(PageQuery<Video> pageQuery) {
		videoDao.pageToAuditVideo(pageQuery);
	}

	/**
	 * 审核端根据用户id查看用户视频
	 *
	 * @param pageIndex
	 * @param pageSize
	 * @param userId
	 * @return
	 */
	@Override
	public GlobalReponse<PageQuery<ToAuditVideoVO>> getUserVideo(int pageIndex, int pageSize, Long userId,Integer type,String keywords) {
		PageQuery<Video> pageQuery = new PageQuery<>();
		pageQuery.setPageNumber(pageIndex);
		pageQuery.setPageSize(pageSize);
		pageQuery.setPara("userId",userId);
		if(type!=null){
			pageQuery.setPara("type",type);
		}
		if(keywords!=null && !keywords.equals("")){
			pageQuery.setPara("keywords",keywords);
		}
		videoDao.getUserVideo(pageQuery);
		List<Video> list = pageQuery.getList();
		List<ToAuditVideoVO> vos = ToAuditVideoVoMapper.MAPPER.toVo(list);
		pageQuery.setList(vos);
		return GlobalReponse.success(pageQuery);
	}

	/**
	 * 审核端根据视频id获取视频详情
	 *
	 * @param videoId
	 * @return
	 */
	@Override
	public GlobalReponse<ToAuditVideoVO> getVideoDetails(Long videoId) {
		Video single = videoDao.createLambdaQuery().andEq(Video::getId, videoId).single();
		if (single != null){
			ToAuditVideoVO videoVO = ToAuditVideoVoMapper.MAPPER.toVo(single);
			if (single.getUploadType()==1){
				User user = userDao.unique(videoVO.getPublishId());
				videoVO.setAccount(user.getAccount());
			}
			if (single.getStatus()==1){
				List<VideoComment> comments = iVideoCommentDao.createLambdaQuery().andEq(VideoComment::getVideoId, single.getId()).andEq(VideoComment::getStatus,1).andEq(VideoComment::getIsDeleted, false).select();
				if (comments != null){
					List<VideoCommentVo> videoCommentVos = VideoCommentVoMapper.MAPPER.toVo(comments);
					videoVO.setComment(videoCommentVos);
				}
			}
			return GlobalReponse.success(videoVO);
		}
		return GlobalReponse.fail("查询失败");
	}

	@Override
	public void pageClassTalkVideo(PageQuery<Video> pageQuery) {
		videoDao.pageClassTalkVideo(pageQuery);
	}

	@Override
	public BigDecimal getVideoScore(Long id) {
		BigDecimal score = videoGradeDao.avgScore(id);
		return score;
	}

	@Override
	public BigDecimal avgScore(Long videoId) {
		return videoGradeDao.avgScore(videoId);
	}

	@Override
	public void pageVideoGrade(PageQuery<VideoGrade> pageQuery) {
		videoGradeDao.pageQuery(pageQuery);
		for (VideoGrade videoGrade : pageQuery.getList()) {
			User user = userDao.unique(videoGrade.getUserId());
			videoGrade.set("user",user);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void delGrade(Long gradeId) {
		VideoGrade videoGrade = videoGradeDao.unique(gradeId);
		videoGrade.setIsDeleted(true);
		videoGradeDao.updateById(videoGrade);
	}

	@Override
	public List<Video> newCheck(Video video) {
		return videoDao.newCheck(video);
	}

	/**
	 * 修改讲一讲点评
	 *
	 * @param userId
	 * @param videoGradeId
	 * @param status
	 * @param remark
	 * @return
	 */
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse updateVideoGrade(Long userId, Long videoGradeId, Integer status, String remark) {
		VideoGrade videoGrade = videoGradeDao.unique(videoGradeId);
		videoGrade.setStatus(status);
		videoGrade.setRefusalCause(remark);
		videoGrade.setUpdateTime(new Date());
		videoGrade.setUpdateBy(userId.toString());
		videoGradeDao.updateTemplateById(videoGrade);
		return GlobalReponse.success("操作成功");
	}

	/**
	 * 获取讲一讲评论
	 *
	 * @param videoId
	 * @return
	 */
	@Override
	public GlobalReponse<List<VideoGrade>> getJyJComment(Long videoId) {
		List<VideoGrade> videoGradeList = videoGradeDao.createLambdaQuery().andEq(VideoGrade::getVideoId, videoId).andEq(VideoGrade::getIsDeleted, false).andIsNotNull(VideoGrade::getRemark).select();
		for (VideoGrade videoGrade : videoGradeList) {
			User user = userDao.unique(videoGrade.getUserId());
			videoGrade.set("user",user);
		}
		return GlobalReponse.success(videoGradeList);
	}

	@Override
	@Transactional(readOnly = false)
	public GlobalReponse saveShareNum(Long userId, Long videoId) {
		Video video = videoDao.single(videoId);
		video.setShareNum(video.getShareNum()+1);
		video.setUpdateTime(new Date());
		video.setUpdateBy(userId.toString());
		videoDao.updateTemplateById(video);
		return GlobalReponse.success();
	}

	/**
	 * 查询推荐视频
	 *
	 * @param pageQuery
	 */
	@Override
	public void selectRecommendVideo(PageQuery<Video> pageQuery) {
		videoDao.selectRecommendVideo(pageQuery);
	}

	/**
	 * 查询关注小视频
	 *
	 * @param pageQuery
	 */
	@Override
	public void selectAttentionVideo(PageQuery<Video> pageQuery) {
		videoDao.selectAttentionVideo(pageQuery);
	}

	/**
	 * 查看同城小视频
	 *
	 * @param pageQuery
	 */
	@Override
	public void selectLocalVideo(PageQuery<Video> pageQuery) {
		videoDao.selectLocalVideo(pageQuery);
	}

	/**
	 * 查看小视频评论
	 * @param videoId
	 * @return
	 */
	@Override
	public GlobalReponse<SmallVideoCommentParentVo> getSmallVideoComment(Long userId, Long videoId) {
		ArrayList<SmallVideoCommentParentVo> parentVos = new ArrayList<>();
		List<VideoComment> selectParent = iVideoCommentDao.createLambdaQuery().andEq(VideoComment::getVideoId,videoId).andEq(VideoComment::getParentId, 0L).andEq(VideoComment::getStatus, 1).andEq(VideoComment::getIsDeleted, false).desc(VideoComment::getCreateTime).select();
		for (VideoComment comment : selectParent) {
			SmallVideoCommentParentVo parentVo = new SmallVideoCommentParentVo();
			BeanUtils.copyProperties(comment,parentVo);
			if (userId!=null){
				Accolade accolade = accoladeDao.getAccolade(userId, comment.getId(), 3);
				if (accolade!=null){
					parentVo.setIsThumpUp(true);
				}else {
					parentVo.setIsThumpUp(false);
				}
			}else {
				parentVo.setIsThumpUp(false);
			}
			List<VideoComment> selectChild = iVideoCommentDao.createLambdaQuery().andEq(VideoComment::getVideoId,videoId).andNotEq(VideoComment::getParentId, 0L).andEq(VideoComment::getParentId,comment.getId()).andEq(VideoComment::getStatus, 1).andEq(VideoComment::getIsDeleted, false).desc(VideoComment::getCreateTime).select();
			ArrayList<SmallVideoCommentChildVo> childVos = new ArrayList<>();
			for (VideoComment videoComment : selectChild) {
				SmallVideoCommentChildVo childVo = new SmallVideoCommentChildVo();
				BeanUtils.copyProperties(videoComment,childVo);
				if (userId!=null){
					Accolade accoladeChild = accoladeDao.getAccolade(userId, videoComment.getId(), 3);
					if (accoladeChild!=null){
						parentVo.setIsThumpUp(true);
					}else {
						parentVo.setIsThumpUp(false);
					}
				}else {
					parentVo.setIsThumpUp(false);
				}
				childVos.add(childVo);
			}
			parentVo.setChildVoList(childVos);
			parentVos.add(parentVo);
		}
		return GlobalReponse.success(parentVos);
	}

	@Override
	public GlobalReponse<SmallVideoDetailsForIdVo> smallVideoDetailForId(Long userId, Long videoId) {
		SmallVideoDetailsForIdVo vo = new SmallVideoDetailsForIdVo();
		Video video = videoDao.unique(videoId);
		//是否关注
		Attention attention = null;
		//是否点赞
		Accolade accolade = null;
		BeanUtils.copyProperties(video, vo);
		if (userId != null) {
			//是否关注
			attention = attentionDao.findByFocusId(userId, video.getPublishId());
			//是否点赞
			accolade = accoladeDao.getAccolade(userId, videoId, 2);
		}
		vo.setIsAttention(null == attention ? false : true);
		vo.setIsLike(null == accolade ? false : true);
		vo.setCommentNum(video.getCommentNum());
		vo.setShareNum(video.getShareNum());
		vo.setThumpUpNum(video.getThumpUpNum());
		return GlobalReponse.success(vo);
	}
}